﻿#ifndef DBSERVICE_H
#define DBSERVICE_H

#include <QtSql/QSqlDatabase>
#include "common.h"
#include "Logger.h"

#include "appmonitor.h"
#include "appmonitorlog.h"
#include "sysmonitorlog.h"

#define SQL_USER_NAME "face"
#define SQL_USER_PASSWD "face_passwd"
#define SQL_DB_NAME "watch.db"

#define SQL_DB_VERSION 6.0

#include "appmonitor.h"

int sendAppMonitorRestartLogAndSaveToDb(AppMonitorLog &log, QString &returnInfo);

class DBService
{
public:
    DBService();

    int openDB(QSqlDatabase & dataBase);

    int checkAndUpdateDB();


    int getSysSettingValue(const QString &key, QString & value);

    int deleteSysSettingValue(const QString &key);

    int insertSysSettingValue(const QString &key, const QString &value);

    int loadAllAppMonitor(list<AppMonitor *> &  monitors);

    int saveOneAppMonitor(AppMonitor &monitor);

    int deleteOneAppMonitor(AppMonitor &monitor);

    int saveOneAppMonitorLog(AppMonitorLog &log);

    int loadMonitorLogs(list<AppMonitorLog *> & logs, QString *monitorName, QString *timeStart, QString *timeEnd, QString *logState, int maxCount = -1);

    int loadMonitorLogsCount(int &count, QString *monitorName, QString *timeStart, QString *timeEnd, QString *logState);

    int deleteMonitorLogs(QString *monitorName, QString *timeStart, QString *timeEnd, QString *logState);

    int getMonitorNames(list<QString> &names);

    int saveOneSysMonitorLog(SysMonitorLog &log);
    
    int deleteSysMonitorLogs(QString *kind, QString *timeStart, QString *timeEnd, bool* isSuccess);

    int loadSysMonitorLogs(list<SysMonitorLog >&logs,QString *kind, QString *timeStart, QString *timeEnd, bool* isSuccess,int maxCount = -1);

    int loadSysMonitorLogsCount(int &count, QString *kind, QString *timeStart, QString *timeEnd, bool* isSuccess);

private:
    int doUpdateDBFrom5_0To6_0();
    int doUpdateDBFrom4_0To5_0();
    int doUpdateDBFrom3_0To4_0();
    int doUpdateDBFrom2_0To3_0();
    int doUpdateDBFrom1_0To2_0();
    int doUpdateDBFrom0_0To1_0();

    int createSysSettingTable();

    int getDBVersion(int & version);

    int saveDBVersion(int version);

    int doUpdateDB();



    int isTableExist(const QString& tableName, bool &exist);

    int queryForInt(const QString  & sql, int &value);

    int queryForString(const QString  & sql, QString &value);

    int execSql(const QString & sql);


 public:

    QSqlDatabase mainDataBase;

    QMutex openDBLock;
};


extern DBService gDBService;

#endif // DBSERVICE_H
